package demo.QLExpress;

import com.alibaba.fastjson.JSONObject;
import com.ql.util.express.ArraySwap;
import com.ql.util.express.InstructionSetContext;
import com.ql.util.express.OperateData;
import com.ql.util.express.instruction.OperateDataCacheManager;

import java.util.Map;

/**
 * @author lingyun.wang on @date 2022/1/11
 */
public class SetValueOperator extends AbstractQLScriptBase {
    private static final String SEPARATOR = ".";

    @Override
    public String getFuncName() {
        return "setValue";
    }

    @Override
    public OperateData executeInner(InstructionSetContext context, ArraySwap list) throws Exception {
        Object cTemp = context.get("tempVar");
        Map temp = new JSONObject();
        if(cTemp == null){
            context.put("tempVar",temp);
        }else if(cTemp instanceof Map){
            temp = (Map) cTemp;
        }else {
            throw new Exception("错误的上下文！！无法将数据放入对象temp。数据临时存放对象(temp)必须为Map类型。temp当前类型为：" + cTemp.getClass());
        }
        String key = list.get(0).toString();
        Object value = list.get(1).getObject(context);
        //处理链式调用，即a.b.c.d
        if(key.contains(SEPARATOR)){
            Map nowNode = temp;
            String[] keyArray = key.split("\\.");
            for (int i = 0; i < keyArray.length -1; i++) {
                Object to = nowNode.get(keyArray[i]);
                if(to == null){
                    to = new JSONObject();
                    nowNode.put(keyArray[i],to);
                    nowNode = (Map)to;
                }else if(to instanceof Map){
                    nowNode = (Map)to;
                }
            }
            nowNode.put(keyArray[keyArray.length-1],value);
        }else {
            temp.put(key,value);
        }
        return OperateDataCacheManager.fetchOperateData((Object)true, (Class)Boolean.class);
    }
}
